import permision from "@/libs/wa-permission/permission.js"
import { Jump } from './jump.js'
import store from '@/store/index.js'
import { getAppVersion, chechVersion } from './upgrade.js'
import { turnAdrr } from '@/api/Ctrls.js'
import { pathToBase64, base64ToPath } from 'image-tools'
import { appid } from '@/common/baseconfig.js'
import { isEmpty } from '@/libs/fn/verify.js'
import { SetDistrict } from "../api/Users.js"
import cookie from '@/utils/auth.js'



const Toast = (content) => {
	return uni.showToast({
		title: content,
		duration: 1500,
		icon: 'none',
		position: 'bottom',
	})
}

const doCopy = (str, toast = true) => {
	let v = str.toString();
	return new Promise((resolve, reject) => {
		uni.setClipboardData({
			data: v,
			success: function() {
				if (!toast) {
					uni.hideToast()
				}
				resolve(true)
			},
			fail() {
				reject(false)
			}
		});
	})

}


const isNetwork = () => {
	uni.getNetworkType({
		success: ({ networkType }) => {
			if (networkType == 'none') {
				Jump({
					url: '/pages/error',
					mode: 4,
					params: {
						msg: '无网络'
					}
				})
			}
			if (networkType == '2g' || networkType == '3g') {
				Toast('当前网络较慢')
			}
		}
	});
}
const onNetwork = () => {
	uni.onNetworkStatusChange(({ isConnected, networkType }) => {
		// store.commit('setting/SET_NETWORK', isConnected)
		if (networkType == 'none') {
			Jump({
				url: '/pages/error',
				mode: 4,
				params: {
					msg: '无网络'
				}
			})
		}
		if (networkType == '2g' || networkType == '3g') {
			Toast('当前网络较慢')
		}
	})

}

//获取UUID
const getUUID = () => {
	try {
		//#ifdef APP
		return new Promise((resolve, reject) => {
			plus.device.getInfo({
				success: function({ uuid }) {
					resolve(uuid)
					console.log(e);
				},
				fail: function(e) {
					console.log('failed: ' + e);
					resolve(false)
				}
			});
		})
		//#endif
		return
	} catch (e) {
		return
		//TODO handle the exception
	}
}




/***
@param name  申请权限的name  例如打开相册
@@return {status}  是否执行下一步
*/
const sysPermis = async (name) => {
	// #ifdef APP
	const result = await permision.requestAndroidPermission(name);
	if (result == -1) {
		//跳转页面权限页
		uni.navigateTo({
			url: '/pages/permision?name=' + name,
		})
		return false
	}
	// #endif
	return true
}


//打开相册
const chooseImage = async () => {
	// #ifdef APP-PLUS
	const status = await sysPermis('android.permission.READ_EXTERNAL_STORAGE')
	if (!status) {
		return Promise.reject(false)
	}
	// #endif
	try {
		return new Promise((resolve, reject) => {
			console.log(123123)
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success({ tempFilePaths, tempFiles }) {
					resolve({
						tempFilePaths,
						tempFiles
					})
					// tempFilePath可以作为img标签的src属性显示图片
				},
				fail(err) {
					console.log('err', err)
					resolve(false)
				},
				complete(e) {
					console.log(e)
				},
			})
		})
	} catch (e) {
		return false
		//TODO handle the exception
	}
}

//打开文件 chooseFile
const chooseFile = async ({ sourceType = ['album', 'camera'] } = {}) => {
	try {
		const res = await sysPermis('android.permission.READ_EXTERNAL_STORAGE');
		console.log('sysPermis[android.permission.READ_EXTERNAL_STORAGE]===>', res)
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success({ tempFilePaths, tempFiles }) {
					resolve({ sucecess: true, tempFilePaths, tempFiles })
					// tempFilePath可以作为img标签的src属性显示图片
				},
				fail(err) {
					// sysPermis('android.permission.READ_EXTERNAL_STORAGE')
					console.log('err', err)
					reject(false)
				},
			})
		})
	} catch (e) {
		console.log(e)
		return Promise.reject(false)
		//TODO handle the exception
	}
}


//选择地址
const chooseLocation = async (isEdit = true) => {
	try {
		return new Promise((resolve, reject) => {
			uni.chooseLocation({
				success: async (res) => {
					const {
						name,
						longitude,
						latitude
					} = res
					const { address, addressComponent, formatted_address } = await turnAdrr( longitude, latitude, false);
					const { country, district, province, city } = addressComponent
					if (isEdit) {
						uni.showModal({
							title: '是否选择该地址作为当前区域？',
							content: name || address,
							success: async ({ confirm, cancel }) => {
								if (confirm) {
									if(cookie.get('Token')){
										const setF = await SetDistrict({
											province: province,
											city: city ||  province,
											district: district,
										})
										if(!setF.success)return this.Toast('设置失败，请重试')
									}
									
									store.commit("address/SET_LOCATIONADDRESS", name || address);
								}
							}
						})
					}
					resolve({
						longitude,
						latitude,
						addressComponent,
						formatted_address,
						success: true,
					})
				},
				fail(e) {
					reject({
						success: false,
					})
				}
			});
		})
	} catch (e) {
		console.log(e)
		return Promise.reject(false)
		//TODO handle the exception
	}
}




const imgToBase64 = (data) => {
	return new Promise((resolve, reject) => {
		pathToBase64(data).then(base64 => {
			resolve(base64)
		}).catch(error => {
			console.error(error)
			reject(error)
		})
	})
}


//指纹识别
const fingerprint = () => {
	return new Promise((resolve, reject) => {
		try {
			// #ifdef APP-PLUS
			uni.startSoterAuthentication({
				requestAuthModes: ['fingerPrint'],
				challenge: '123456',
				success(res) {
					resolve(true)
				},
				fail(err) {
					resolve(false)
				},
			})
			// #endif

		} catch (e) {
			resolve(false)
		}

	})
}


// 获取定位信息
const getLocation = () => {
	let location = {};

	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'wgs84 ',
			geocode: true,
			//#ifdef APP-PLUS
			type: 'gcj02 ',
			//#endif
			isHighAccuracy: true, //开启高精度定位
			success: async (res) => {
				console.log('getLocation', res)

				// Toast('获取定位信息', res);
				location.latitude = res.latitude;
				location.longitude = res.longitude;

				store.commit("address/SET_LOCATIONOB", {
					latitude: res.latitude,
					longitude: res.longitude
				});

				const address = await turnAdrr(res.longitude, res.latitude)




				// //#ifdef APP-PLUS
				// location.area = res.address.city;
				// //#endif

				resolve({
					address: address,
					latitude: res.latitude,
					longitude: res.longitude,
				})

			},
			fail: function(err) {
				console.log("获取定位失败", err);
				uni.showToast({
					title: '获取地址失败，将导致部分功能不可用',
					icon: 'none'
				});
				resolve(false)

			}
		});
	})



}


//扫码
const doScanCode = () => {
	return new Promise((resolve, reject) => {
		uni.scanCode({
			scanType: ['qrCode'],
			success: function({ result }) {
				resolve(result)
			},
			fail() {
				resolve(false)
			}
		});
	})
}


//支付
const payment = (item) => {
	return new Promise((resolve, reject) => {
		// const {
		// 	prepayId,
		// 	wechatpayNonce,
		// 	wechatpayRequestId,
		// 	wechatpaySignature,
		// 	wechatpaySignatureType,
		// 	wechatpayTimestamp
		// } = item;


		uni.requestPayment({
			"provider": "wxpay",
			...item,
			success(res) {
				resolve(true)
			},
			fail(e) {
				console.log('支付失败', e)
				Toast('支付失败')
				resolve(false)
			}
		})
	})
}

const openServiceChat = (url) => {
	let config = store.state.general.config
	let urls = config[715]
	return new Promise((resolve, reject) => {
		wx.openCustomerServiceChat({
			// extInfo: { url: urls },
			// corpId: 'ww1d1220dd86ae9658',
			success(res) {}
		})
	})
}

const makePhoneCall = (phone) => {
	return new Promise((resolve, reject) => {
		uni.makePhoneCall({
			phoneNumber: phone,
			success: function() {
				console.log('拨打电话成功');
			},
			fail: function(err) {
				console.log('拨打电话失败：', err);
			}
		});
	})
}



// 截取指定字符前/后的字符 不包含指定字符（obj：原字符串；character：指定字符；state：0前面部分1后面部分）
const getCaption = (obj, character, state) => {
	var index = obj.indexOf(character);
	if (state == 0) {
		obj = obj.substring(0, index);
	} else {
		obj = obj.substring(index + character.length, obj.length);
	}
	return obj;
}

// 截取指定字符前/后的字符 包含指定字符（obj：原字符串；character：指定字符；state：0前面部分1后面部分）
const getCaption1 = (obj, character, state) => {
	var index = obj.indexOf(character);
	if (state == 0) {
		obj = obj.substring(0, index + character.length);
	} else {
		obj = obj.substring(index, obj.length);
	}
	return obj;
}

// 获取地址中的省市区
const getProvinces = (poiaddress) => {
	let provinces = {};
	let reg = /.+?(省|市|自治区|自治州|县|区)/g;
	let ssqList = poiaddress.match(reg);
	ssqList.map((item, index) => {
		switch (index) {
			case 0: // 省、自治区、直辖市、特别行政区
				provinces.province = item;
				break;
			case 1: // 地级市、地区、自治州、盟
				if (provinces.province.lastIndexOf("省") != -1 || provinces.province.lastIndexOf("自治区") != -
					1) {
					provinces.city = item;
				} else if (provinces.province.lastIndexOf("市") != -1) {
					provinces.county = item;
					provinces.city = "市辖区"; // location.province
				} else {
					provinces.county = item;
				}
				break;
			case 2: // 市辖区、县级市、县、自治县、旗、自治旗、特区、林区
				if (provinces.province.lastIndexOf("省") != -1 || provinces.province.lastIndexOf("自治区") != -
					1) {
					provinces.county = item;
				}
				break;
			default:
				break;
		}

	});
	return provinces;
}

/**
  	打开链接或页面
	@param {browser}  = String  默认浏览器打开browser
 */
const openUrl = async ({ url, type = 'browser', isToast = false }) => {
	if (!url) return Toast('系统升级中');

	if (isToast) {
		let res = await uni.showModal({
			title: '打开链接?',
			content: '即将打开链接：' + url,
		});
		const { confirm, cancel } = res[0] || res[1];
		if (cancel) {
			return false;
		}
	}

	//webview直接打开
	if (type == 'webview') {
		return Jump('/pages/webview/webview?url=' + url);
	}

	const system = uni.getSystemInfoSync()

	//H5打开外部链接
	// #ifdef H5
	if (system.platform == 'ios') {
		// 如果是iOS平台(window.open在ios平台会被拦截)
		window.location.href = url;
	} else {
		window.open(url)
	}
	// #endif

	//APP打开链接
	// #ifdef APP-PLUS
	plus.runtime.openURL(url, err => {
		if (plus.os.name == "Android") {
			plus.runtime.launchApplication({
				pname: "com.android.browser",
				extra: { url: url }
			}, function(err) {
				console.log(err);
			});
		} else if (plus.os.name == "iOS") {
			plus.runtime.launchApplication({ action: url }, function(e) {
				console.log(e);
			});
		}
	});
	// #endif

	// let reg = new RegExp('http')
	// // url不包含http 跳转页面
	// if (!reg.test(url)) return Jump(url);
}


const guid = () => {
	function S4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}
	return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}


/**
 * 首页公告第一条弹框
 * @param idx    // 公告idx
 * @returns boolean      （true|| false）
 */

const openNotice = (idx) => {
	if (!uni.getStorageSync('newsidx')) {
		uni.setStorageSync('newsidx', idx);
		return true;
	} else {
		if (uni.getStorageSync('newsidx') == idx) return false
		uni.setStorageSync('newsidx', idx);
		return true
	}
}


const payJump = (data, payType) => {
	const system = uni.getSystemInfoSync()
	switch (Number(payType)) {
		//微信支付
		case 11:
			// #ifdef APP-PLUS
			///app微信；拉起小程序支付
			const { openlink } = JSON.parse(data)

			openURL({
				url: openlink,
				openType: ' '
			})

			// Jump('/pages/webview/webview?title=微信收银台&url=' + openlink)
			// plus.share.getServices(function(res) {
			// 	let sweixin = null;
			// 	for (let i = 0; i < res.length; i++) {
			// 		let t = res[i];
			// 		if (t.id == 'weixin') {
			// 			sweixin = t;
			// 		}
			// 	}
			// 	if (sweixin) {
			// 		// { 
			// 		// 	"order_no": "P542139103454493965", 
			// 		// 	"trx_no": "100223030859193698", 
			// 		// 	"payee_name": "大富购电子商务", 
			// 		// 	"original_id": "gh_030d020d002f", 
			// 		// 	"app_id": "d3g2NmE5ZWEwY2VkZjc5ZjMx", 
			// 		// 	"product_name": "大富购电子商务云南有限公司", 
			// 		// 	"order_amout": 58,
			// 		// }
			// 		sweixin.launchMiniProgram({
			// 			id: 'gh_030d020d002f',
			// 			type: 0,
			// 			path: '/pages/payIndex/payIndex?rc_result=' + data
			// 		});
			// 	}
			// }, (res) => {
			// 	console.log(JSON.stringify(res));
			// });
			// #endif
			// #ifdef H5
			// 微信H5支付  直接跳转webview
			const { openlink } = JSON.parse(data)
			window.location.href = openlink;
			// if (system.platform == 'ios') {
			// 	//如果是iOS平台(window.open在ios平台会被拦截)
			// } else {
			// 	window.location.href = openlink
			// 	// Jump('/pages/webview/webview?title=微信收银台&url=' + openlink)
			// }
			// #endif
			return
			break;
		case 12:
			// #ifdef APP-PLUS
			// /支付宝APP支付跳转webview
			// window.location.href = data
			openUrl({
				url: data
			})
			// Jump('/pages/webview/webview?title=支付宝收银台&url=' + data)
			// #endif
			// #ifdef H5
			window.location.href = data
			// #endif
			// if (system.platform == 'ios') {
			// 	window.location.href = data
			// } else {

			// }
			break;
		default:
			return false
	}
}

//对象清除null或''属性
const removeProperty = (obj) => {
	if (!obj) return {};
	Object.keys(obj).forEach(item => {
		if (obj[item] === '' || obj[item] === undefined || obj[item] === null || obj[item] === 'null')
			delete obj[item]
	})
	return obj
}


const imgMatch = (str = "") => {
	return str.match(/(https?:\/\/[^\s,]+)/g);
}
const getAppId = () => {
	// #ifdef APP
	return uni.getAccountInfoSync().miniProgram.appId
	// #endif

}

const toMiniProgram = ({ path, extraData }) => {
	return new Promise((resolve, reject) => {
		uni.navigateToMiniProgram({
			appId: 'wxdabdc8f6210f4e2a', // 填入目标小程序的 appId
			path: path, // 打开的页面路径，如果为空则打开首页
			envVersion: 'trial',
			extraData: {
				...extraData
			},
			success(res) {
				// 打开成功的回调
			},
			fail(err) {
				// 打开失败的回调
			}
		});
	})

}
const openEmbeddedMiniProgram = ({ path, extraData }) => {
	return new Promise((resolve, reject) => {
		// wx.openEmbeddedMiniProgram
	})

}

const getUrlParams = (url) => {
	console.log('getUrlParams', url)
	// \w+ 表示匹配至少一个(数字、字母及下划线), [\u4e00-\u9fa5]+ 表示匹配至少一个中文字符
	let pattern = /(\w+|[\u4e00-\u9fa5]+)=(\w+|[\u4e00-\u9fa5]+)/ig;
	let result = {};
	url.replace(pattern, ($, $1, $2) => {
		result[$1] = $2;
	})
	return result

}




export {
	doCopy,
	Toast,
	Jump,
	getAppVersion,
	chechVersion,
	fingerprint,
	isNetwork,
	onNetwork,
	doScanCode,
	getUUID,
	chooseImage,
	chooseFile,
	chooseLocation,
	imgToBase64,
	getCaption,
	getCaption1,
	getProvinces,
	openUrl,
	openNotice,
	guid,
	sysPermis,
	payJump,
	getLocation,
	removeProperty,
	imgMatch,
	payment,
	openServiceChat,
	makePhoneCall,
	getAppId,
	toMiniProgram,
	getUrlParams,
}